package cn.com.dcsgo.service.impl;

import cn.com.dcsgo.common.PageInfo;
import cn.com.dcsgo.constants.CoreConstant;
import cn.com.dcsgo.domain.dto.SysUserQueryDTO;
import cn.com.dcsgo.domain.dto.SysUserSaveDTO;
import cn.com.dcsgo.domain.dto.SysUserUpdateDTO;
import cn.com.dcsgo.domain.po.SysDept;
import cn.com.dcsgo.domain.po.SysUser;
import cn.com.dcsgo.mapper.SysDeptMapper;
import cn.com.dcsgo.mapper.SysRoleMapper;
import cn.com.dcsgo.mapper.SysUserMapper;
import cn.com.dcsgo.service.SysUserService;
import cn.com.dcsgo.utils.ConverterUtils;
import cn.hutool.core.lang.Assert;
import com.github.pagehelper.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * SysUserServiceImpl
 *
 * @author Dcsgo
 * @since 20/5/2025 下午 3:23
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl implements SysUserService {
    private final SysUserMapper sysUserMapper;
    private final SysDeptMapper sysDeptMapper;
    private final SysRoleMapper sysRoleMapper;

    @Override
    public SysUser getOne(String username, String password) {
        return sysUserMapper.selectByUsernameAndPassword(username, password);
    }

    @Override
    public SysUser getOneWithDeptNameAndLeaderName(Long userId) {
        SysUser user = sysUserMapper.selectByPrimaryKey(userId);
        if (user != null) {
            // 获取直属领导信息
            if (user.getLeaderId() != null) {
                SysUser leader = sysUserMapper.selectByPrimaryKey(user.getLeaderId());
                if (leader != null) {
                    user.setLeaderName(leader.getNickName());
                } else {
                    log.error("数据不一致!用户:{}的直属领导:{}不存在", user.getUserId(), user.getLeaderId());
                }
            }

            // 获取部门信息
            if (user.getDeptId() != null) {
                SysDept dept = sysDeptMapper.selectByPrimaryKey(user.getDeptId());
                if (dept != null) {
                    user.setDeptName(dept.getDeptName());
                } else {
                    log.error("数据不一致!用户:{}所在的部门:{}不存在", user.getUserId(), user.getDeptId());
                }
            }
        }

        return user;
    }

    @Override
    public List<String> getAllPermission() {
        return sysUserMapper.selectAllPermission();
    }

    @Override
    public List<String> getPermissions(Long userId) {
        return sysUserMapper.selectPermissionsByUserId(userId);
    }

    @Override
    public PageInfo<SysUser, SysUserQueryDTO> page(PageInfo<SysUser, SysUserQueryDTO> pageInfo) {
        // 分页条件查询
        Page<SysUser> page = this.startPage(pageInfo.getPageNumber(), pageInfo.getPageSize());
        List<SysUser> userList;
        if (pageInfo.getParams() != null) {
            userList = sysUserMapper.selectBySysUserQueryDTO(pageInfo.getParams());
        } else {
            userList = sysUserMapper.selectAll();
        }

        // 封装分页信息
        pageInfo.setList(userList);
        pageInfo.setTotalPage(page.getPages());
        pageInfo.setTotalCount(page.getTotal());
        if (CollectionUtils.isEmpty(userList)) {
            return pageInfo;
        }

        //封装用户的部门名称
        Set<Long> deptIds = userList.stream().map(SysUser::getDeptId).collect(Collectors.toSet());
        if (!CollectionUtils.isEmpty(deptIds)) {
            List<SysDept> deptList = sysDeptMapper.selectByDeptIds(deptIds);
            if (!CollectionUtils.isEmpty(deptList)) {
                Map<Long, SysDept> deptMap = deptList.stream().collect(Collectors.toMap(SysDept::getDeptId, sysDept -> sysDept));
                userList.forEach(user -> {
                    if (user.getDeptId() != null) {
                        SysDept dept = deptMap.get(user.getDeptId());
                        if (dept != null) {
                            user.setDeptName(dept.getDeptName());
                        } else {
                            log.error("数据不一致!用户id:{}的对应部门id:{}不存在", user.getUserId(), user.getDeptId());
                        }
                    }
                });
            }
        }

        //封装用户的直属领导
        Set<Long> leaderIds = userList.stream().map(SysUser::getLeaderId).collect(Collectors.toSet());
        if (!CollectionUtils.isEmpty(leaderIds)) {
            List<SysUser> leaderList = sysUserMapper.selectByUserIds(leaderIds);
            if (!CollectionUtils.isEmpty(leaderList)) {
                Map<Long, SysUser> leaderMap = leaderList.stream().collect(Collectors.toMap(SysUser::getUserId, sysUser -> sysUser));
                userList.forEach(user -> {
                    if (user.getLeaderId() != null) {
                        SysUser leader = leaderMap.get(user.getLeaderId());
                        if (leader != null) {
                            user.setLeaderName(leader.getNickName());
                        } else {
                            log.error("数据不一致!用户id:{}的直属领导id:{}不存在", user.getUserId(), user.getLeaderId());
                        }
                    }
                });
            }
        }

        return pageInfo;
    }

    @Transactional(rollbackFor = {Throwable.class})
    @Override
    public int add(SysUserSaveDTO saveDTO) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(saveDTO, sysUser);

        sysUser.setUserType(CoreConstant.USER_TYPE_NORMAL);
        sysUser.setPassword(DigestUtils.md5DigestAsHex(CoreConstant.DEFAULT_PASSWORD.getBytes()));
        sysUser.setCreateBy(getUsername());
        sysUser.setCreateTime(new Date());

        return sysUserMapper.insertSelective(sysUser);
    }

    @Transactional(rollbackFor = {Throwable.class})
    @Override
    public int update(SysUserUpdateDTO updateDTO) {
        SysUser updateData = sysUserMapper.selectByPrimaryKey(updateDTO.getUserId());
        Assert.notNull(updateData, "更新的用户不存在");

        ConverterUtils.syncFieldsWithNullOnEqual(updateDTO, updateData, "userId");
        updateData.setUpdateBy(getUsername());
        updateData.setUpdateTime(new Date());

        updateData.setCreateBy(null);
        updateData.setCreateTime(null);
        updateData.setAvatar(null);
        updateData.setPassword(null);
        updateData.setLoginDate(null);
        updateData.setLoginIp(null);

        return sysUserMapper.updateByPrimaryKeySelective(updateData);
    }

    @Transactional(rollbackFor = {Throwable.class})
    @Override
    public int remove(Long userId) {
        int row = sysUserMapper.deleteByPrimaryKey(userId);
        row += sysRoleMapper.deleteUserRoleByUserId(userId);
        return row;
    }

    @Transactional(rollbackFor = {Throwable.class})
    @Override
    public int resetPassword(Long userId) {
        SysUser resetUser = new SysUser();
        resetUser.setUserId(userId);
        resetUser.setPassword(DigestUtils.md5DigestAsHex(CoreConstant.DEFAULT_PASSWORD.getBytes()));
        return sysUserMapper.updateByPrimaryKeySelective(resetUser);
    }
}
